<template>
  <div class="app-container">
    <div
      v-show="
        !adjustPriceModifyInfo.visible &&
        !detailInfo.visible &&
        !detailListInfo.visible
      "
    >
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter
          v-model:query="filterInfo.query.queryMap"
          :query-more-json="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clear-type="clearType"
          :slip-select-request="slipSelectRequest"
        >
        </NewPageFilter>
        <el-button @click="detailListInfo.visible = true">明细页</el-button>
      </div>
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-approve>
            <el-button :disabled="!canFlowBtn" @click="btnFlow('', 'approve')"
              >批准
            </el-button>
          </template>
          <template v-slot:filter-reject>
            <el-button :disabled="!canFlowBtn" @click="btnFlow('', 'reject')"
              >驳回
            </el-button>
          </template>
          <template v-slot:filter-refuse>
            <el-button :disabled="!canFlowBtn" @click="btnFlow('', 'refuse')"
              >拒绝
            </el-button>
          </template>
          <template v-slot:filter-delete>
            <el-button :disabled="!canDelete" @click="del()">删除</el-button>
          </template>
        </NewPageFilter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowClassName"
        @handleEvent="handleEvent"
        @sortChange="sortChange"
        @pageInfo="pageInfo"
      >
        <template v-slot:col-orderNo="scope">
          <span
            v-if="$permission('adjustPrice:details')"
            class="slip-edit"
            @click="showDetail(scope.row)"
            >{{ scope.row.orderNo }}</span
          >
          <span v-else>{{ scope.row.orderNo || '-' }}</span>
        </template>
      </table-container>
    </div>
    <adjust-price-modify
      v-if="adjustPriceModifyInfo.visible"
      v-model:visible="adjustPriceModifyInfo.visible"
      :table-row="adjustPriceModifyInfo.tableRow"
      :title="adjustPriceModifyInfo.title"
      @returnModify="returnModify"
    />

    <!-- 明细信息 -->
    <adjust-price-detail
      v-if="detailInfo.visible"
      v-model:visible="detailInfo.visible"
      :table-row="detailInfo.tableRow"
      @returnBack="getList"
    />
    <detailList
      v-if="detailListInfo.visible"
      v-model:visible="detailListInfo.visible"
      @callback="getList"
    ></detailList>
    <set-preference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      :group-level-show="false"
      @callback="setPreferenceCallback"
    />
    <advanced-search
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:form-data="advancedSearchInfo.data"
      :field-list="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
  </div>
</template>

<script setup name="adjustPrice">
import {
  getAdjustPriceOrderPage,
  submitAdjustPriceOrder,
  approveAdjustPriceOrder,
  rejectAdjustPriceOrder,
  refuseAdjustPriceOrder,
  recallAdjustPriceOrder,
  salesReviewAdjustPriceOrder,
  delAdjustPriceOrder,
  downloadFileAdjustPriceOrders,
} from '@/api/purch'
import { getBusinessKeyById } from '@/api/flowable'
import { ElMessage, ElLoading } from 'element-plus'
const AdjustPriceModify = defineAsyncComponent(() => import('./modify'))
const AdjustPriceDetail = defineAsyncComponent(() => import('./detail'))
const detailList = defineAsyncComponent(() => import('./detailList'))

import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'

const { proxy } = getCurrentInstance()
const emit = defineEmits()

// 过滤相关配置
const filterInfo = reactive({
  sortArr: [],
  copyQueryMap: {},
  query: {
    customizeUserVO: {},
    queryMap: {
      supplierAuth: {
        asTbName: 'adjust_price_order',
        columnName: 'supplier_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'supplierAuth',
      },
    },
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'button',
      label: '新增',
      event: create,
      show: proxy.$permission('adjustPrice:add'),
    },
    {
      type: 'slot',
      label: '批准',
      value: 'approve',
      show:
        proxy.$permission('adjustPrice:approve') &&
        proxy.$store.state.permission.systemConfig
          .adjust_price_order_approval_type == 1,
    },
    {
      type: 'slot',
      label: '驳回',
      value: 'reject',
      show:
        proxy.$permission('adjustPrice:reject') &&
        proxy.$store.state.permission.systemConfig
          .adjust_price_order_approval_type == 1,
    },
    {
      type: 'slot',
      label: '拒绝',
      value: 'refuse',
      show:
        proxy.$permission('adjustPrice:refuse') &&
        proxy.$store.state.permission.systemConfig
          .adjust_price_order_approval_type == 1,
    },
    {
      type: 'slot',
      label: '删除',
      value: 'delete',
      show: proxy.$permission('adjustPrice:remove'),
    },
    {
      type: 'button',
      label: '下载附件',
      event: downloadFile,
      show: proxy.$permission('adjustPrice:downloadFile'),
    },
  ],
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '提交',
        event: submit,
        show: proxy.$permission('adjustPrice:submit'),
        ifRender: function (row) {
          return (row.status === 1 || row.status === 4) && !row.platOrderNo
        },
      },
      {
        label: '修改',
        event: update,
        show: proxy.$permission('adjustPrice:update'),
        ifRender: function (row) {
          return (row.status === 1 || row.status === 4) && !row.platOrderNo
        },
      },
      {
        label: '删除',
        event: del,
        show: proxy.$permission('adjustPrice:remove'),
        ifRender: function (row) {
          return (row.status === 1 || row.status === 4) && !row.platOrderNo
        },
      },
      {
        label: '批准',
        event: (row) => btnFlow(row, 'approve'),
        show: proxy.$permission('adjustPrice:approve'),
        ifRender: checkIfRenderBtnFlow,
      },
      {
        label: '驳回',
        event: (row) => btnFlow(row, 'reject'),
        show: proxy.$permission('adjustPrice:reject'),
        ifRender: checkIfRenderBtnFlow,
      },
      {
        label: '拒绝',
        event: (row) => btnFlow(row, 'refuse'),
        show: proxy.$permission('adjustPrice:refuse'),
        ifRender: checkIfRenderBtnFlow,
      },
      {
        label: '撤回',
        event: recall,
        show: proxy.$permission('adjustPrice:recall'),
        ifRender: checkIfRenderRecall,
      },
      {
        label: '销审',
        event: salesReview,
        show: proxy.$permission('adjustPrice:salesReview'),
        ifRender: checkIfRenderSalesReview,
      },
    ],
  },
})
const adjustPriceModifyInfo = reactive({
  visible: false,
  title: '',
  tableRow: {},
})
const detailInfo = reactive({
  visible: false,
  tableRow: {},
})
const detailListInfo = reactive({
  visible: false,
})
const preferenceInfo = reactive({
  visible: false,
})
const advancedSearchInfo = reactive({
  visible: false,
  data: {},
})
let page = reactive({
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})
const clearType = ref(true)
const slipSelectRequest = ref(true)

const canFlowBtn = computed(() => {
  return (
    tableInfo.selections.length &&
    tableInfo.selections.filter((row) => row.status !== 2).length === 0
  )
})
const canDelete = computed(() => {
  return (
    tableInfo.selections.length &&
    tableInfo.selections.filter(
      (row) => (row.status !== 1 && row.status !== 4) || row.platOrderNo
    ).length === 0
  )
})
const toPage = computed(() => {
  return proxy.$store.state.settings.toPage
})

watch(
  () => proxy.$router.currentRoute.value.name,
  (to, from) => {
    if (!from) return
    if (
      from.includes('myPendingDetail') ||
      from.includes('myFinishedDetail') ||
      from.includes('myApplyDetail')
    ) {
      getList()
    }
  },
  {
    deep: true,
  }
)

let stopWatch = function () {}
onActivated(() => {
  stopWatch = watch(
    () => toPage.value,
    (val) => {
      if (val) {
        let menus = proxy.$store.state.permission.defaultMenus
        menus.forEach((item) => {
          if (item.children) {
            item.children.forEach((el) => {
              if (el.code === 'adjustPrice' && el.url === val.url) {
                detailInfo.visible = false
                adjustPriceModifyInfo.visible = false
                detailListInfo.visible = false
                if (val.urlType === 1) {
                  getList()
                } else if (val.urlType === 2) {
                  detailInfo.visible = true
                  detailInfo.tableRow = { id: val.businessId }
                }
                proxy.$store.dispatch('settings/toPage', '')
              }
            })
          }
        })
      }
    },
    {
      deep: true,
      immediate: true,
    }
  )
})
onDeactivated(() => {
  stopWatch()
})
onMounted(() => {
  setData()
})

function setData() {
  let obj = {
    statusValue: {
      label: '状态',
      value: 'statusValue',
      componentType: 'select-model',
      code: 'adjust_price_order_status',
      show: false,
      hidden: true,
    },
  }
  tableInfo.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  filterInfo.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  getCustomize()
}
// 批准/驳回/拒绝
function checkIfRenderBtnFlow(row) {
  return (
    proxy.$store.state.permission.systemConfig
      .adjust_price_order_approval_type == 1 && row.status === 2
  )
}
// 销审
function checkIfRenderSalesReview(row) {
  return (
    row.status === 6 &&
    proxy.$store.state.permission.systemConfig
      .adjust_price_order_approval_type != 0
  )
}
// 撤回
function checkIfRenderRecall(row) {
  return (
    (row.status === 2 ||
      (row.status === 6 &&
        proxy.$store.state.permission.systemConfig
          .adjust_price_order_approval_type == 0)) &&
    !row.platOrderNo
  )
}
function downloadFile() {
  downloadFileAdjustPriceOrders(filterInfo.query).then((res) => {
    if (res) {
      proxy.$fn.parseExcel(res)
    }
  })
}
function pageInfo(obj) {
  page = obj
}
async function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.visible = true
}
async function advancedSearchCallback(obj) {
  let arr = [
    {
      asTbName: 'adjust_price_order',
      columnName: 'supplier_id',
      queryType: 'IN',
      queryCategory: 'AND',
      value: 'supplierAuth',
    },
  ]
  filterInfo.query.queryMap = {}
  filterInfo.query.queryDtoList = [...obj.queryDtoList, ...arr]
  advancedSearchInfo.data = obj.data
  await getList()
  clearType.value = !clearType.value
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
}
function returnModify() {
  if (adjustPriceModifyInfo.tableRow && adjustPriceModifyInfo.tableRow.id) {
    getList()
  } else {
    search()
  }
}
// 获取列表
function getList() {
  tableInfo.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页

  advancedSearchInfo.data = {}
  filterInfo.query.queryDtoList = []
  tableInfo.initCurpage = Math.random()
  tableInfo.refresh = Math.random()
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
  }
}
//创建
function create() {
  adjustPriceModifyInfo.title = '创建调价单'
  adjustPriceModifyInfo.tableRow = {}
  adjustPriceModifyInfo.visible = true
}
//更新
function update(row) {
  getBusinessKeyById({
    businessKey: row.orderNo,
    businessType: 'adjustOrder',
  }).then((res) => {
    if (res.success) {
      sessionStorage.setItem('storeRowId', row.id)
      if (res.data?.processInstanceId) {
        proxy.$fn.setFlowData(res.data, '', proxy.$route)
      } else {
        //修改
        adjustPriceModifyInfo.title = '修改调价单'
        adjustPriceModifyInfo.tableRow = { ...row }
        adjustPriceModifyInfo.visible = true
      }
    }
  })
}
//展示明细
function showDetail(row) {
  getBusinessKeyById({
    businessKey: row.orderNo,
    businessType: 'adjustOrder',
  }).then((res) => {
    if (res.success) {
      sessionStorage.setItem('storeRowId', row.id)
      if (res.data?.processInstanceId) {
        proxy.$fn.setFlowData(res.data, '', proxy.$route)
      } else {
        detailInfo.tableRow = row
        detailInfo.id = row.id
        detailInfo.visible = true
      }
    }
  })
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
//提交
function submit(row) {
  const ids = _getIds(row)
  let data = {
    flowTaskCommentDto: { approvalType: 'submit' },
    processDefinitionKey: 'adjustOrder',
    orderIds: ids,
  }
  submitAdjustPriceOrder(data).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
// 审批/拒绝/驳回按钮审批原因弹窗
function btnFlow(row, code) {
  const ids = _getIds(row)
  const currentBtnFlow = {
    title: '',
    api: null,
  }
  if (code === 'approve') {
    currentBtnFlow.api = approveAdjustPriceOrder
    const data = {
      orderIds: ids,
    }
    currentBtnFlow.api(data).then((resp) => {
      if (resp && resp.success) {
        getList()
      }
    })
    return
  } else if (code === 'reject') {
    currentBtnFlow.title = '驳回'
    currentBtnFlow.api = rejectAdjustPriceOrder
  } else if (code === 'refuse') {
    currentBtnFlow.title = '拒绝'
    currentBtnFlow.api = refuseAdjustPriceOrder
  }
  proxy
    .$prompt('请输入' + currentBtnFlow.title + '理由', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValidator: proxy.$fn.maxString200,
      inputErrorMessage: currentBtnFlow.title + '理由不能超过200字符',
    })
    .then(({ value }) => {
      const data = {
        orderIds: ids,
        checkOpt: value,
      }
      currentBtnFlow.api(data).then((resp) => {
        if (resp && resp.success) {
          getList()
        }
      })
    })
}
// 撤回
function recall(row) {
  const ids = _getIds(row)
  recallAdjustPriceOrder(ids).then((res) => {
    if (res && res.success) {
      getList()
      ElMessage.success({
        message: '操作成功',
        duration: 3000,
        showClose: true,
      })
    } else {
      ElMessage.error({
        message: res.msg,
        duration: 3000,
        showClose: true,
      })
    }
  })
}
// 销审
function salesReview(row) {
  const ids = _getIds(row)
  salesReviewAdjustPriceOrder(ids).then((res) => {
    if (res && res.success) {
      getList()
      ElMessage.success({
        message: '操作成功',
        duration: 3000,
        showClose: true,
      })
    } else {
      ElMessage.error({
        message: res.msg,
        duration: 3000,
        showClose: true,
      })
    }
  })
}
//删除
function del(row) {
  const ids = _getIds(row)
  proxy.$handleAPI('delete', delAdjustPriceOrder, ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function _getIds(row) {
  let ids = []
  if (row && row.id) {
    ids = [row.id]
  } else {
    if (tableInfo.selections.length > 0) {
      ids = tableInfo.selections.map((row) => row.id)
    }
  }
  return ids
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.data = {}
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
  search()
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey:
      'AdjustPriceOrderList-com.slip.spd.entity.vo.purch.AdjustPriceOrderVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.query.customizeUserVO = data
      tableInfo.fieldList = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.searchList,
        data.detail
      )
      filterInfo.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.query.queryMap,
      }
      filterInfo.searchList = searchInfo.searchList
      filterInfo.searchList.forEach((item) => {
        item.event = search
        if (item.value === 'supplierName') {
          item.query = {
            sort: 'create_time desc',
            supplierAuth: 'supplierId',
          }
        }
      })
      filterInfo.copyQueryMap = proxy.$fn.deepClone(filterInfo.query.queryMap)
      slipSelectRequest.value = _slipSelectRequest
      tableInfo.api = getAdjustPriceOrderPage
      getList()
    }
  })
}
function sortChange(column) {
  if (filterInfo.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.sortArr)
    filterInfo.sortArr = arr
    filterInfo.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}
</script>

<style scoped></style>
